package com.edu.demo.service.impl;

import com.edu.demo.constant.UserConstant;
import com.edu.demo.entity.*;
import com.edu.demo.mapper.RoleMapper;
import com.edu.demo.mapper.SysMenuMapper;
import com.edu.demo.utils.SecurityUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @ClassName: PermissionService
 * @Description:
 * @Author: jxw
 * @Date: 2023-01-28
 */
@Service("ps")
public class PermissionService {

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Autowired
    private RoleMapper roleMapper;

    public boolean hasPerm(String per){
        if(per.equals("common:file:download")) return true;
        if(Strings.isEmpty(per)) return false;

        LoginUser user = SecurityUtils.getLoginUser();
        if(Objects.isNull(user)) return false;
        Set<String> permissions = user.getPermissions();
        boolean contains = permissions.contains(per);

        return contains;
    }

    public Set<String> getMenuPermission(SysUser user)
    {
        Set<String> perms = new HashSet<String>();
        // 管理员拥有所有权限
        Role role = roleMapper.selectRoleByUserIdAndType(UserConstant.ADMIN_TYPE, user.getId());
        user.setRole(role);
        if(!Objects.isNull(role)){
            user.setRole(role);
            Set<SysMenu> menus = sysMenuMapper.selectMenusByRole(role.getId());
            Set<String> perms1 = menus.stream().map(m -> m.getPerms()).collect(Collectors.toSet());
            perms.addAll(perms1);
        }
        return perms;
    }

    public Set<String> getMenuPermission(Student user)
    {
        Set<String> perms = new HashSet<String>();
        Role role = roleMapper.selectRoleByUserIdAndType(UserConstant.STUDENT_TYPE, user.getId());
        if(!Objects.isNull(role)){
            user.setRole(role);
            Set<SysMenu> menus = sysMenuMapper.selectMenusByRole(role.getId());
            Set<String> perms1 = menus.stream().map(m -> m.getPerms()).collect(Collectors.toSet());
            perms.addAll(perms1);
        }
        return perms;
    }
    public Set<String> getMenuPermission(Teacher user)
    {
        Set<String> perms = new HashSet<String>();
        Role role = roleMapper.selectRoleByUserIdAndType(UserConstant.TEACHER_TYPE, user.getId());
        if(!Objects.isNull(role)){
            user.setRole(role);
            Set<SysMenu> menus = sysMenuMapper.selectMenusByRole(role.getId());
            Set<String> perms1 = menus.stream().map(m -> m.getPerms()).collect(Collectors.toSet());
            perms.addAll(perms1);
        }
        return perms;
    }


}
